package com.engine.cese.duss.srm.util;

import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.upgradetool.wscheck.Util;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Title: Ecology9
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2021-04-02
 * @Description: 通用工具类
 * @ModifyLog:
 **/

public class GenUtil {
    private static Pattern NUMBER_PATTERN = Pattern.compile("[0-9]+");
    //建模权限重构
    public static void getNewModeRight(String userid, String formmodeid, String id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight( true );
        modeRightInfo.editModeDataShare( Util.getIntValue( userid ), Util.getIntValue( formmodeid ), Util.getIntValue( id ) );
    }

    //判断采购类型转换成名称
    public static String getCglx2Name(String cglx) {
        String cglxName = "";
        switch (cglx) {
            case "0":
                cglxName = "WL";
                break;
            case "1":
                cglxName = "GC";
                break;
            case "2":
                cglxName = "ZL";
                break;
            case "3":
                cglxName = "YS";
                break;
            case "4":
                cglxName = "FW";
                break;
        }
        return cglxName;
    }

    //生成任务编码
    public static String generTaskCode(String bmlx) {
        RecordSet rs = new RecordSet();
        String newdqlsh = "1";
        String newdqbm = "";
        String currentDate = DateUtil.getCurrentDate();
        String curDate = currentDate.substring( 4, 10 );
        String curYear = currentDate.substring( 0, 4 );
        if (curDate.equals( "-01-01" )) {
            newdqlsh = autoGenericCode( newdqlsh, 6 );
            String bmlxName = getCglx2Name( bmlx );
            newdqbm = "CGRW-" + bmlxName + "-" + curYear + "-" + newdqlsh;
            String sql1 = "update uf_serial_number set dqrq=?,dqlsh=?,dqbm=?";
            rs.executeUpdate( sql1, new Object[]{currentDate, newdqlsh, newdqbm} );
        } else {
            String sql = "select step,dqlsh from uf_serial_number where bmlx=?";
            rs.executeQuery( sql, bmlx );
            if (rs.next()) {
                int step = weaver.general.Util.getIntValue( rs.getString( "step" ) );//步值
                int dqlsh = weaver.general.Util.getIntValue( rs.getString( "dqlsh" ) );//当前流水号
                newdqlsh = autoGenericCode( weaver.general.Util.getNumStr( dqlsh + step ), 6 );
                String bmlxName = getCglx2Name( bmlx );
                newdqbm = "CGRW-" + bmlxName + "-" + curYear + newdqlsh;
                String sql1 = "update uf_serial_number set dqrq=?,dqlsh=?,dqbm=? where bmlx=?";
                rs.executeUpdate( sql1, new Object[]{currentDate, newdqlsh, newdqbm, bmlx} );
            } else {
                newdqlsh = autoGenericCode( newdqlsh, 6 );
                String bmlxName = getCglx2Name( bmlx );
                newdqbm = "CGRW-" + bmlxName + "-" + curYear + newdqlsh;
                String sql1 = "insert into uf_serial_number (dqrq,step,dqlsh,bmlx,dqbm) values (?,?,?,?,?)";
                rs.executeUpdate( sql1, new Object[]{currentDate, "1", newdqlsh, bmlx, newdqbm} );
            }
        }

        return newdqbm;
    }

    //不够位数的在前面补0，保留num的长度位数字
    public static String autoGenericCode(String code, int num) {
        String result = "";
        result = String.format( "%0" + num + "d", Integer.parseInt( code ) );
        return result;
    }

    //获取采购需求明细未勾选的条数
    public static boolean getDtlCounts(String mainid, String cglx) {
        RecordSet rs = new RecordSet();
        boolean flag = true;
        String sql = "select count(id) as counts from " + getCgxqTableType( cglx ) + "_dt1 where mainid=? and cfbj=0";
        rs.executeQuery( sql, mainid );
        rs.next();
        int counts = weaver.general.Util.getIntValue( rs.getString( "counts" ) );
        if (counts > 0) {
            flag = false;
        }
        return flag;
    }

    //根据采购需求类型获取表单
    public static String getCgxqTableType(String cglx) {
        String table = "";
        BaseBean baseBean = new BaseBean();
        switch (cglx) {
            case "0":
                table = baseBean.getPropValue( "SrmMdTab", "cgxqwl" );
                break;
            case "1":
                table = baseBean.getPropValue( "SrmMdTab", "cgxqgc" );
                break;
            case "2":
                table = baseBean.getPropValue( "SrmMdTab", "cgxqzl" );
                break;
            case "3":
                table = baseBean.getPropValue( "SrmMdTab", "cgxqys" );
                break;
            case "4":
                table = baseBean.getPropValue( "SrmMdTab", "cgxqfw" );
                break;
        }
        return table;
    }

    //根据采购任务类型获取表单
    public static String getCgrwTableType(String cglx) {
        String table = "";
        BaseBean baseBean = new BaseBean();
        switch (cglx) {
            case "0":
                table = baseBean.getPropValue( "SrmMdTab", "cgrwwl" );
                break;
            case "1":
                table = baseBean.getPropValue( "SrmMdTab", "cgrwgc" );
                break;
            case "2":
                table = baseBean.getPropValue( "SrmMdTab", "cgrwzl" );
                break;
            case "3":
                table = baseBean.getPropValue( "SrmMdTab", "cgrwys" );
                break;
            case "4":
                table = baseBean.getPropValue( "SrmMdTab", "cgrwfw" );
                break;
        }
        return table;
    }

    //获取插入数据id
    public static String getRwbh2Id(String rwbh, String cglx) {
        RecordSet rs = new RecordSet();
        String sql = "select id from " + getCgrwTableType( cglx ) + " where rwbh=?";
        rs.executeQuery( sql, rwbh );
        rs.next();
        String id = weaver.upgradetool.wscheck.Util.null2String( rs.getString( "id" ) );
        return id;
    }

    //获取formmodeid
    public static String getFormmodeId(String cglx) {
        String tableName = getCgrwTableType( cglx );
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select m.id from modeinfo m left join WORKFLOW_BILL b on m.formid = b.id where b.tablename = ?", tableName );
        rs.next();
        String formmodeid = weaver.upgradetool.wscheck.Util.null2String( rs.getString( "id" ) );
        return formmodeid;
    }

    //    --商务分计算规则
    //(2).基准价
    public static String getBasePrice(String jzj, String zpl, String fpl, String wspbbj) {
        String pl = CalUtil.fMultiply( "1", CalUtil.fSubtract( CalUtil.fDivide( wspbbj, jzj, 6 ), "1" ), 6 );
        String df = "";
        if (CalUtil.fCompare( pl, "0" ) > 0) {
            df = CalUtil.fAdd( CalUtil.fMultiply( CalUtil.fabs( pl ), zpl, 2 ), "100" );//得分
        } else if (CalUtil.fCompare( pl, "0" ) == 0) {
            df = "100";//得分
        } else if (CalUtil.fCompare( pl, "0" ) < 0) {
            df = CalUtil.fAdd( CalUtil.fMultiply( CalUtil.fabs( pl ), fpl, 2 ), "100" );//得分
        }
        return df;
    }

    //(2).平均价
    public static String getAvgPrice(String pbbj, String jgjsbl, String zpl, String fpl, String pjj) {
        String jzj = CalUtil.fMultiply( pjj, jgjsbl, 2 );//基准价
        String pl = CalUtil.fMultiply( "1", CalUtil.fSubtract( CalUtil.fDivide( pbbj, jzj, 6 ), "1" ), 6 ); //偏离
        String df = "";
        if (CalUtil.fCompare( pl, "0" ) > 0) {
            df = CalUtil.fAdd( CalUtil.fMultiply( CalUtil.fabs( pl ), zpl, 2 ), "100" );//得分
        } else if (CalUtil.fCompare( pl, "0" ) == 0) {
            df = "100";//得分
        } else if (CalUtil.fCompare( pl, "0" ) < 0) {
            df = CalUtil.fAdd( CalUtil.fMultiply( CalUtil.fabs( pl ), fpl, 2 ), "100" );//得分
        }
        return df;
    }

    //   --技术分计算规则
    public static String getTechCalRule(String lc, String cglxd, String sfkc,String gysmc,String dfb) {
        String df = "";
        RecordSet rs = new RecordSet();
        rs.writeLog( "getTechCalRule-----------sfkc=", sfkc);
        if (CalUtil.fCompare( sfkc, "0" ) == 0) {//扣除
            String sql = "select sum(pf)-max(pf)-min(pf) as jsdf,count(1) as counts from (\n" +
                    "SELECT t.pfr,sum(REGEXP_SUBSTR(to_char(t1.pf), '[^,]+', 1, LEVEL)) as pf\n" +
                    "FROM  "+dfb+" t left join "+dfb+"_dt1 t1\n" +
                    "on t.id=t1.mainid where lc=? and cglxd=? and REGEXP_SUBSTR(to_char(t1.gysmc), '[^,]+', 1, LEVEL)=?\n" +
                    "CONNECT BY LEVEL <= REGEXP_COUNT(to_char(t1.gysmc), '[^,]+')\n" +
                    "       AND t1.ROWID = PRIOR t1.ROWID\n" +
                    "       AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL\n" +
                    "group by t.pfr)";
            rs.executeQuery(sql,lc,cglxd,gysmc);
            rs.next();
            rs.writeLog(sql,lc+","+cglxd+","+gysmc);
            String jsdf =Util.null2String( rs.getString( "jsdf" ) );
            String counts =Util.null2String( rs.getString( "counts" ) );
            rs.writeLog("jsdf=",jsdf);
            rs.writeLog("counts=",counts);
            df = CalUtil.fDivide( jsdf, CalUtil.fSubtract( counts, "2" ), 2 );
            rs.writeLog("df=",df);
        } else {//不扣除
            String sql = "select sum(pf) as jsdf,(count(1))as counts from (\n" +
                    "SELECT t.pfr,sum(REGEXP_SUBSTR(to_char(t1.pf), '[^,]+', 1, LEVEL)) as pf\n" +
                    "FROM  "+dfb+" t left join "+dfb+"_dt1 t1\n" +
                    "on t.id=t1.mainid where lc=? and cglxd=? and REGEXP_SUBSTR(to_char(t1.gysmc), '[^,]+', 1, LEVEL)=?\n" +
                    "CONNECT BY LEVEL <= REGEXP_COUNT(to_char(t1.gysmc), '[^,]+')\n" +
                    "       AND t1.ROWID = PRIOR t1.ROWID\n" +
                    "       AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL\n" +
                    "group by t.pfr)";
            rs.executeQuery(sql,lc,cglxd,gysmc);
            rs.next();
            rs.writeLog(sql,lc+","+cglxd+","+gysmc);
            String jsdf =Util.null2String( rs.getString( "jsdf" ) );
            String counts =Util.null2String( rs.getString( "counts" ) );
            rs.writeLog("jsdf=",jsdf);
            rs.writeLog("counts=",counts);
            df = CalUtil.fDivide( jsdf, counts, 2 );
            rs.writeLog("df=",df);
        }
        return df;
    }

    public static String getPjj(String lc, String cglxd, String sfkc,String kbjghq) {
        RecordSet rs = new RecordSet();
        String pjj = "";
        String sql = "select sum(t1.wsbj1) as wsbj,sum(t1.wsbj1)-max(t1.wsbj1)-min(t1.wsbj1) as pbbj,count(t1.gys) as counts\n" +
                "from "+kbjghq+" t left join "+kbjghq+"_dt1 t1 \n" +
                "on t.id=t1.mainid where t.lc=? and t.cglxd=? and t1.sfyxtb=0";
        rs.executeQuery( sql, lc, cglxd);
        rs.next();
        String wsbj = Util.null2String( rs.getString( "wsbj" ) );//投标报价
        String pbbj = Util.null2String( rs.getString( "pbbj" ) );//评标报价
        String counts = Util.null2String( rs.getString( "counts" ) );//人数
        if ("0".equals( sfkc )) {//扣除最高最低
            pjj = CalUtil.fDivide( pbbj, CalUtil.fSubtract( counts, "2" ), 6 );
        } else if ("1".equals( sfkc )) {//不扣除
            pjj = CalUtil.fDivide( wsbj, counts, 6 );
        }
        rs.writeLog( "pjj=",pjj );
        return pjj;
    }

    public static String getId2Gysmc(String id) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( " select gysmc from view_srm_zc_gys where id=?", id );
        rs.next();
        String gysmc = Util.null2String( rs.getString( "gysmc" ) );
        return gysmc;
    }
    // 根据loginid获取人员ID
    public static String getHrmIdByLoginid(String id){
            RecordSet rs = new RecordSet();
            rs.execute("select loginid from hrmresource where id = '" + id + "'");
            rs.next();
            String loginid =  Util.null2String(rs.getString(1));
            return loginid;
    }

    public static String getId2Gysmcs(String ids) {
        RecordSet rs = new RecordSet();
        String[] str = ids.split( "," );
        String gysmcs = "";
        for (String id : str) {
            rs.executeQuery( "select gysmc from view_srm_zc_gys where id =?", id );
            rs.next();
            String gysmc = Util.null2String( rs.getString( "gysmc" ) );
            gysmcs += "".equals( gysmcs ) ? gysmc : "," + gysmc;
        }
        return gysmcs;
    }

    public static String getId2Sl(String id) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( " select sl from uf_SRM_sl where id=?", id );
        rs.next();
        String sl = Util.null2String( rs.getString( "sl" ) );
        return sl;
    }

    //获取根据任务单ID获取任务池最小Id
    public static Map<String, String> getRwdmxids(String ids) {
        RecordSet rs = new RecordSet();
        Map<String, String> map = new HashMap<>();
        rs.executeQuery( "select wm_concat(id) as rwmxids,mainid from uf_cgrw_wl_dt1 " +
                "where mainid =(select min(mainid)from uf_cgrw_wl_dt1 " +
                "where mainid in (" + ids + ")) group by mainid" );
        rs.next();
        String rwmxids = Util.null2String( rs.getString( "rwmxids" ) );
        String mainid = Util.null2String( rs.getString( "mainid" ) );
        map.put( "rwmxids", rwmxids );
        map.put( "mainid", mainid );
        return map;
    }

    //获取项目名称
    public static String getCgRwdids(String ids) {
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select wm_concat(distinct minid) from \n" +
                "(SELECT ROW_NUMBER() OVER(PARTITION BY xmmc,xqbh,wlbm ORDER BY minid asc) rn,UU.*\n" +
                "FROM (select a.id as minid,a.xmmc,a.xqbh,b.wlbm from uf_cgrw_wl a,uf_cgrw_wl_dt1 b \n" +
                "where a.id=b.mainid  and mainid in(" + ids + "))UU)AA\n" +
                "where RN=1 " );
        rs.next();
        String rwdids = Util.null2String( rs.getString( 1 ) );
        return rwdids;
    }

    //流程表单根据requestid获取ID
    public static String getRequestid2Id(String requestid) {
        BaseBean baseBean = new BaseBean();
        String zbcglx = baseBean.getPropValue( "SrmWfTab", "zbcglx" );
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select id from " + zbcglx + " where requestid=?", requestid );
        rs.next();
        String id = Util.null2String( rs.getString( "id" ) );
        return id;
    }

    //流程表单根据requestid获取ID
    public static String getCglxd2Name(String requestid) {
        BaseBean baseBean = new BaseBean();
        String zbcglx = baseBean.getPropValue( "SrmWfTab", "zbcglx" );
        RecordSet rs = new RecordSet();
        rs.executeQuery( "select cglxmc from " + zbcglx + " where requestid=?", requestid );
        rs.next();
        String cglxmc = Util.null2String( rs.getString( "cglxmc" ) );
        return cglxmc;
    }

    //根据采购立项单、当期日期获取人员在线表的人员ID
    public static String getCglxd2RyId(String cglxd, String curdate) {
        RecordSet rs = new RecordSet();
        String sql = "select wm_concat(ryid) from uf_ryzxb where cglxd=? and zxrq=?";
        rs.executeQuery( sql, cglxd, curdate );
        rs.next();
        String ryid = Util.null2String( rs.getString( 1 ) );
        return ryid;
    }

    //根据表单和字段获取下拉框值
    public static String getSelectItem(int billid, String fieldname, String selectvalue) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.selectvalue,t1.selectname from workflow_selectitem t1 left join workflow_billfield t2\n" +
                "on t1.fieldid=t2.id where abs(t2.billid)=? and t2.fieldname=? and t1.selectvalue=?";
        rs.executeQuery( sql, billid, fieldname, selectvalue );
        rs.next();
        String selectname = Util.null2String( rs.getString( "selectname" ) );
        return selectname;
    }

    //随机生成四位字母不重复的字符串
    public static String genrateStr(int count) {
        String[] source = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        StringBuilder stringBuilder = new StringBuilder(count);
        int len = source.length;
        for(int i=0;i<count;i++){
            final int index = new Random().nextInt(len);
            stringBuilder.append( source[index] );
        }
        return stringBuilder.toString();
    }

    //根据loginID获取客户模块loginid名称
    public static String getCrmLoginId2Name(String loginid){
        RecordSet rs = new RecordSet();
        String sql = "select name from crm_customerinfo where portalloginid=?";
        rs.executeQuery( sql, loginid );
        rs.next();
        String name = weaver.general.Util.null2String( rs.getString( "name" ) );
        return name;
    }

    //根据loginID获取客户模块loginid名称
    public static String getOaLoginId2Name(String loginid){
        RecordSet rs = new RecordSet();
        String sql = "select lastname from hrmresource where loginid=?";
        rs.executeQuery( sql, loginid );
        rs.next();
        String lastname = weaver.general.Util.null2String( rs.getString( "lastname" ) );
        return lastname;
    }

    //截取数字
    public static String getNumbers(String content) {
        Matcher matcher = NUMBER_PATTERN.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    //获取付款条件名称
    public static String getFktjkxxName(String id) {
        RecordSet rs = new RecordSet();
        String sql = "select fktjkxx from uf_fktj where id=?";
        rs.executeQuery(sql,id);
        rs.next();
        String fktjkxxname = Util.null2String(rs.getString("fktjkxx"));
        return fktjkxxname;
    }

    //获取供应商代号
    public static String getGysdh(String cglxd,String gysid) {
        RecordSet rs = new RecordSet();
        String sql = "select dh from uf_bidguestinfo where cglxd=? and gysid=?";
        rs.executeQuery(sql,cglxd,gysid);
        rs.next();
        String dh = Util.null2String(rs.getString("dh"));
        return dh;
    }
    //获取报价次数
    public static int getGysBjCounts(String cglxd,String gysid) {
        RecordSet rs = new RecordSet();
        String sql = "select count(gysmc)+1 as counts from uf_bjxxb where cglxd=? and gysid=?";
        rs.executeQuery(sql,cglxd,gysid);
        rs.next();
        int counts = Util.getIntValue(rs.getString("counts"));
        return counts;
    }

    public static String getFktjkxxId(String gysmc,String lc,String cglxd,String table) {
        RecordSet rs = new RecordSet();
        String sql = " select t3.fktjkxx from "+table+" t left join " +
                " "+table+"_dt3 t3 on t.id=t3.mainid\n" +
                " where t.gysmc=? and t.lc=? and t.cglxd =? and t3.gysxzx=1";
        rs.executeQuery(sql,gysmc,lc,cglxd);
        rs.next();
        String fktjkxx = Util.null2String(rs.getString("fktjkxx"));
        return fktjkxx;
    }
    //数字转布尔类型
    public static boolean getNum2Bool(String num){
        boolean flag = true;
        if("1".equals(num)){
            flag = false;
        }
        return flag;
    }

    //参数日期是否大于当前日期
    public static boolean IsGrethanCurDate(String date) {
        boolean flag = false;
        long ts1 = 0L;
        long ts2 = 0L;
        try {
            if(date.length()>10){
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                Date d1 = sdf.parse( date );
                 ts1 = d1.getTime();
                Date d2 = sdf.parse( DateUtil.getFullDate() );
                 ts2 = d2.getTime();
            }else {
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
                Date d1 = sdf.parse( date );
                 ts1 = d1.getTime();
                Date d2 = sdf.parse( DateUtil.getCurrentDate() );
                 ts2 = d2.getTime();
            }
            if((ts1 - ts2)>=0){
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
